#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2024. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
Time: 2024/08/17
Author:
Description:
"""
from typing import List, Tuple

import sqlalchemy
from vulcanus.database.proxy import MysqlProxy, RedisProxy
from vulcanus.log.log import LOGGER
from vulcanus.restful.resp.state import SUCCEED, DATABASE_QUERY_ERROR, DATABASE_UPDATE_ERROR
from vulcanus.restful.response import BaseResponse
from zeus.user_access_service.database.table import Feature
from zeus.user_access_service.app import cache


class FeatureProxy(MysqlProxy):
    """
    feature related table operation
    """

    def query_activated_features(self) -> Tuple[str, List[dict]]:
        """
        Query all activated features from the database.

        Returns:
            A tuple containing a status code and a list of dictionaries, each representing a feature.
        """
        try:
            rows = self.session.query(Feature).filter(Feature.enable == True).all()
            if rows:
                RedisProxy.redis_connect.delete(cache.ACTIVATED_FEATURES)
                RedisProxy.redis_connect.sadd(cache.ACTIVATED_FEATURES, *[row.feature_name for row in rows])
            return SUCCEED, [{"feature_name": row.feature_name, "feature_id": row.feature_id} for row in rows]
        except sqlalchemy.exc.SQLAlchemyError as error:
            LOGGER.error(error)
            LOGGER.error("Query active feature info failed.")
            return DATABASE_QUERY_ERROR, []

    def query_all_features(self) -> Tuple[str, List[dict]]:
        """
        Query all features from the database.

        Returns:
            A tuple containing a status code and a list of dictionaries, each representing a feature.
        """
        try:
            rows = self.session.query(Feature).all()
            return SUCCEED, [row.to_dict() for row in rows]
        except sqlalchemy.exc.SQLAlchemyError as error:
            LOGGER.error(error)
            LOGGER.error("Query active feature info failed.")
            return DATABASE_QUERY_ERROR, []

    def update_feature(self, updated_features: List[dict]) -> str:
        """
        Update the features in the database.

        Args:
            updated_features: A list of dictionaries, each representing a feature to be updated.

        Returns:
            A status code indicating whether the update was successful.
        """
        try:
            self.session.bulk_update_mappings(Feature, updated_features)
            self.session.commit()
            RedisProxy.redis_connect.delete(cache.ACTIVATED_FEATURES)
            return SUCCEED
        except sqlalchemy.exc.SQLAlchemyError as error:
            LOGGER.error(error)
            self.session.rollback()
            return DATABASE_UPDATE_ERROR